package com.etc.myblog.ser;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.myblog.biz.CommentBiz;
import com.etc.myblog.entity.Article;
import com.etc.myblog.entity.Comment;
import com.etc.myblog.entity.User;


public class CommentSer extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String dateString = sdf.format(new Date());
//		System.out.println(dateString);
		CommentBiz biz = new CommentBiz();
		if (request.getParameter("tag") != null) {
			String tag = request.getParameter("tag");
			if (tag != "" && tag.equals("postComm")) {
				String postUserId = request.getParameter("uid");	//获取发表评论人(登录用户)的用户Id
				String articleId = request.getParameter("artuid");	//获取该文章的Id(此Id可查出文章拥有者)
				String Comcontent = request.getParameter("comcontent");//获取评论人的评论内容
				
				if (postUserId != null && articleId != null) {
					Comment comment = new Comment();
					//保存文章信息
					Article article = new Article();
					article.setArticleId(Integer.parseInt(articleId));
					//保存评论人的信息
					User user = new User();
					user.setUserId(Integer.parseInt(postUserId));
					//开始封装数据
					comment.setArticle(article);
					comment.setUser(user);
					comment.setCommentContent(Comcontent);
					comment.setCommentTime(new Date());
					comment.setCommentClick(new Random().nextInt(100)+1);
					//把该评论上传到数据库
					biz.addComment(comment);
					//request.getRequestDispatcher("/ArticleSer?tag=detail&articleid="+articleId).forward(request, response);
					response.sendRedirect("/MyBlog/ArticleSer?tag=detail&articleid="+articleId);
				}
			} else if (tag != "" && tag.equals("showMyComm")) {
				//获取登录者的Id
				User user = (User)request.getSession().getAttribute("user");
				List<Comment> list = biz.findBypostUserId(user.getUserId());
				request.setAttribute("list", list);
				request.getRequestDispatcher("user/commentList.jsp").forward(request, response);
			} else if (tag != "" && tag.equals("deleteComm")) {		//删除评论
				if (request.getParameter("comId") != null) {
					String comId = request.getParameter("comId");
					if (comId != "") {
						biz.deleteComment(Integer.parseInt(comId));
						response.sendRedirect("/MyBlog/CommentSer?tag=showMyComm");	//跳转到查看评论页面
					}
				}
				
			}
		}
		
	}
}
